package com.sx.pipeline.ui.setting.profile

import android.Manifest
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.drawable.Drawable
import android.net.Uri
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.PermissionUtils
import com.blankj.utilcode.util.ToastUtils
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.CustomTarget
import com.bumptech.glide.request.transition.Transition
import com.gyf.immersionbar.ImmersionBar
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.luck.picture.lib.utils.DateUtils
import com.lxj.xpopup.XPopup
import com.permissionx.guolindev.PermissionX
import com.sx.mvvmlibs.base.NoVMBaseActivity
import com.sx.pipeline.BR
import com.sx.pipeline.R
import com.sx.pipeline.app.base.CYDataBindingBaseActivity
import com.sx.pipeline.app.config.Constant.*
import com.sx.pipeline.arouth.RoutePath
import com.sx.pipeline.databinding.ActProfileBinding
import com.sx.pipeline.custom.dialog.CustomCommonPicket
import com.sx.pipeline.utils.CompressHelper
import com.sx.pipeline.utils.GlideEngine
import com.sx.pipeline.utils.PermissionHelper
import com.yalantis.ucrop.UCrop
import com.yalantis.ucrop.UCropImageEngine
import java.io.File


/**
 * @Author: YY
 * @Date: 2022/4/5
 * @Description: 我的资料
 */
@Route(path = RoutePath.Setting.PROFILE)
class ProfileActivity :
    CYDataBindingBaseActivity<ActProfileBinding, ProfileVM>(R.layout.act_profile),
    View.OnClickListener {

    private var headUrl: String = ""
    override fun initData() {
        mBinding.setVariable(BR.onClick, this)
        mBinding.titleBar.leftView.setOnClickListener {
            finish()
        }
        // 设置状态栏字体颜色
        ImmersionBar.with(this)
            .fitsSystemWindows(true)
            .statusBarColor(R.color.color_0188ff)
            .statusBarDarkFont(false)
            .init()

        //请求个人信息接口
        mViewModel.updateUserInfo()
    }

    override fun initViewObservable() {
        super.initViewObservable()
        observe(mViewModel.userInfoDataEvent) {
            //头像
            headUrl = it?.avatar.toString()
            Glide.with(this).load(it?.avatar).placeholder(R.mipmap.ic_default_head)
                .into(mBinding.ivHead)
            //昵称
            mBinding.sbNickname.rightText = it?.userName
            mBinding.sbGender.rightText = it?.sex
            //手机号
            mBinding.sbPhone.rightText = it?.phone
            //职务
            mBinding.sbDepart.rightText = it?.postName
            //组织名称
            mBinding.sbOrganizationDepartment.rightText = it?.deptName
            //上级姓名
            mBinding.sbDirectSuperior.rightText = it?.parentName
            //上级手机号
            mBinding.sbSuperiorPhone.rightText = it?.parentPhone
        }

        observe(mViewModel.uploadDataEvent) {
            headUrl = it.toString()
        }
    }


    override fun onClick(v: View?) {
        when (v?.id) {
            //选择头像
            R.id.iv_head -> {
                PermissionHelper.requestTip(this,"上次头像需要授权相机和读写权限",object :
                    PermissionUtils.SimpleCallback{
                    override fun onGranted() {
                        chooseHead()
                    }

                    override fun onDenied() {
                        ToastUtils.showShort("请授权后再继续操作")
                    }
                },Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.CAMERA)


//                PermissionX.init(this)
//                    .permissions(
//                        Manifest.permission.READ_EXTERNAL_STORAGE,
//                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
//                        Manifest.permission.CAMERA,
//                    )
//                    .onExplainRequestReason { scope, deniedList ->
//                        scope.showRequestReasonDialog(
//                            deniedList,
//                            "核心基础功能基于这些权限,请允许,否则影响app正常使用",
//                            "确认",
//                            "取消"
//                        )
//                    }
//                    .onForwardToSettings { scope, deniedList ->
//                        scope.showForwardToSettingsDialog(
//                            deniedList,
//                            "您需要手动在“设置”中允许必要的权限",
//                            "确定",
//                            "取消"
//                        )
//                    }
//                    .request { allGranted, _, _ ->
//                        if (allGranted) {
//                            chooseHead()
//                        } else {
//                            ToastUtils.showShort(getString(R.string.txt_these_permissions_are_denied))
//                        }
//                    }
            }
            //选择性别
            R.id.sb_gender -> {
                val list = ArrayList<String>()
                list.add(0, "男")
                list.add(1, "女")
                val popup = CustomCommonPicket(this, getString(R.string.txt_choose_gender))
                popup.setPickerData(list)
                popup.setCommonPickerListener { _, data ->
                    mBinding.sbGender.rightText = data
                }
                XPopup.Builder(this)
                    .borderRadius(42f)
                    .isDarkTheme(false)
                    .asCustom(popup)
                    .show()
            }
            //选择职务
            R.id.sb_depart -> {
//                val list = ArrayList<String>()
//                list.add(0, "管理员")
//                list.add(1, "班长")
//                val popup = CustomCommonPicket(this, getString(R.string.txt_choose_depart))
//                popup.setPickerData(list)
//                popup.setCommonPickerListener { _, data ->
//                    ToastUtils.showShort(data)
//                }
//                XPopup.Builder(this)
//                    .borderRadius(42f)
//                    .isDarkTheme(false)
//                    .asCustom(popup)
//                    .show()
            }
            //选择组织部门
            R.id.sb_organization_department -> {
//                val list = ArrayList<String>()
//                list.add(0, "行政部")
//                list.add(1, "财务部")
//                val popup =
//                    CustomCommonPicket(this, getString(R.string.txt_choose_organization_department))
//                popup.setPickerData(list)
//                popup.setCommonPickerListener { _, data ->
//                    ToastUtils.showShort(data)
//                }
//                XPopup.Builder(this)
//                    .borderRadius(42f)
//                    .isDarkTheme(false)
//                    .asCustom(popup)
//                    .show()
            }
            //修改昵称
            R.id.sb_nickname -> {
                ARouter.getInstance().build(RoutePath.Setting.UPDATENICK).withString("type", "1")
                    .withString("name", mBinding.sbNickname.rightText.toString())
                    .navigation(this, REQUEST_SET_NICKNAME)
            }
            //修改直属上级
            R.id.sb_direct_superior -> {
//                ARouter.getInstance().build(RoutePath.Setting.UPDATENICK).withString("type", "2")
//                    .navigation(this, REQUEST_DIRECTSUPERIOR)
            }
            //修改上级电话
            R.id.sb_superior_phone -> {
//                ARouter.getInstance().build(RoutePath.Setting.UPDATE_SPRPRIOR_PHONE)
//                    .navigation(this, REQUEST_SURPRIOR_PHONE)
            }
            //提交修改用户信息
            R.id.tv_keep -> {
                mViewModel.updateUser(
                    headUrl,
                    mBinding.sbGender.rightText.toString(),
                    mBinding.sbNickname.rightText.toString()
                )
            }
        }
    }

    @Suppress("DEPRECATION")
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode != RESULT_OK) return
        when (requestCode) {
            PictureConfig.CHOOSE_REQUEST -> {
                if (requestCode == PictureConfig.CHOOSE_REQUEST || requestCode == PictureConfig.REQUEST_CAMERA) {
                    val result = PictureSelector.obtainSelectorList(data)
                    for (i in 0 until result.size) {
                        val media = result[i]
                        Glide.with(this).load(File(media.cutPath))
                            .into(mBinding.ivHead)
                        //压缩图片
                        val inputBitmap = BitmapFactory.decodeFile(media.cutPath)
                        val compressFile = CompressHelper.compressQuality(this, inputBitmap)
                        mViewModel.uploadImage(compressFile)
                    }
                }
            }
            //修改昵称
            REQUEST_SET_NICKNAME -> {
                val name = data?.getStringExtra("name").toString()
                mBinding.sbNickname.rightText = name
            }
            //修改上级
            REQUEST_DIRECTSUPERIOR -> {
                val name = data?.getStringExtra("name").toString()
                mBinding.sbDirectSuperior.rightText = name
            }
            //修改上级电话
            REQUEST_SURPRIOR_PHONE -> {
                val name = data?.getStringExtra("name").toString()
                mBinding.sbSuperiorPhone.rightText = name
            }
        }
    }

    private fun chooseHead() {
        PictureSelector.create(this)
            .openGallery(SelectMimeType.ofImage())
            .setMaxSelectNum(1)
            .setImageEngine(GlideEngine.createGlideEngine())
            .setCropEngine { fragment, currentLocalMedia, dataSource, requestCode ->
                val currentCropPath = currentLocalMedia.availablePath
                val inputUri: Uri =
                    if (PictureMimeType.isContent(currentCropPath) || PictureMimeType.isHasHttp(
                            currentCropPath
                        )
                    ) {
                        Uri.parse(currentCropPath)
                    } else {
                        Uri.fromFile(File(currentCropPath))
                    }
                val fileName = DateUtils.getCreateFileName("CROP_") + ".jpg"
                val destinationUri = Uri.fromFile(File(getSandboxPath(), fileName))
                val dataCropSource = java.util.ArrayList<String>()
                for (i in dataSource.indices) {
                    val media = dataSource[i]
                    dataCropSource.add(media.availablePath)
                }
                val uCrop = UCrop.of(inputUri, destinationUri, dataCropSource)
                //options.setMultipleCropAspectRatio(buildAspectRatios(dataSource.size()));
                //options.setMultipleCropAspectRatio(buildAspectRatios(dataSource.size()));
                val options: UCrop.Options = UCrop.Options()
                options.setCircleDimmedLayer(false)
                options.withAspectRatio(1f, 1f)
                options.setShowCropGrid(true)
                uCrop.withOptions(options)
                uCrop.setImageEngine(object : UCropImageEngine {
                    override fun loadImage(
                        context: Context,
                        url: String,
                        imageView: ImageView
                    ) {
                        Glide.with(context).load(url).override(180, 180).into(imageView)
                    }

                    override fun loadImage(
                        context: Context,
                        url: Uri,
                        maxWidth: Int,
                        maxHeight: Int,
                        call: UCropImageEngine.OnCallbackListener<Bitmap>
                    ) {
                        Glide.with(context).asBitmap().override(maxWidth, maxHeight)
                            .load(url).into(object : CustomTarget<Bitmap?>() {
                                override fun onResourceReady(
                                    resource: Bitmap,
                                    transition: Transition<in Bitmap?>?
                                ) {
                                    call.onCall(resource)
                                }

                                override fun onLoadFailed(errorDrawable: Drawable?) {
                                    call.onCall(null)
                                }

                                override fun onLoadCleared(placeholder: Drawable?) {}
                            })
                    }
                })
                uCrop.start(this, fragment, requestCode)
            }
            .forResult(PictureConfig.CHOOSE_REQUEST)
    }

    /**
     * 创建自定义输出目录
     *
     * @return
     */
    private fun getSandboxPath(): String {
        val externalFilesDir: File = applicationContext.getExternalFilesDir("")!!
        val customFile = File(externalFilesDir.absolutePath, "Sandbox")
        if (!customFile.exists()) {
            customFile.mkdirs()
        }
        return customFile.absolutePath + File.separator
    }


}